<?php
// 引入数据库连接代码
include 'conn.php';

// 处理用户注册的函数
function userRegister($conn, $username, $password, $confirmPassword, $email, $phone)
{
    // 验证用户名是否已存在
    $checkUsernameSQL = "SELECT * FROM users WHERE username = '$username'";
    $checkUsernameResult = mysqli_query($conn, $checkUsernameSQL);

    if (mysqli_num_rows($checkUsernameResult) > 0) {
        return "用户名已存在";
    }

    // 验证密码是否一致
    if ($password !== $confirmPassword) {
        return "密码和确认密码不一致";
    }

    // 验证手机格式是否正确
    if (!preg_match("/^\d{11}$/", $phone)) {
        return "手机号格式不正确";
    }

    // 验证邮箱格式是否正确
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return "邮箱格式不正确";
    }

    // 对密码进行哈希加密
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // 插入用户数据到数据库
    $insertUserSQL = "INSERT INTO users (username, password, email, phone) VALUES ('$username', '$hashedPassword', '$email', '$phone')";

    if (mysqli_query($conn, $insertUserSQL)) {
        return "注册成功";
    } else {
        return "注册失败：" . mysqli_error($conn);
    }
} 

// 处理用户提交的注册表单
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 获取用户输入
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);
    $confirmPassword = mysqli_real_escape_string($conn, $_POST['confirmPassword']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);

    // 调用函数处理用户注册
    $registrationResult = userRegister($conn, $username, $password, $confirmPassword, $email, $phone);

    // 根据注册结果进行相应处理
    if ($registrationResult === "注册成功") {
        echo '<script>alert("注册成功"); window.location.href = "login.html";</script>';
    } else {
        echo '<script>alert("' . $registrationResult . '"); window.location.href = "register.html";</script>';
    }

    // 关闭数据库连接
    mysqli_close($conn);
    exit(); // 终止脚本执行
}
?>
